iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Mobile Development

我將點燃Swiftの大海系列 第 18

Day18. Swift一定要會の留言板實作篇 (3)

  • 分享至 

  • xImage
  •  

btnSort

我們今天要回到 MainViewController 中設定 button 的作用
先從排序按鈕開始,一步一步設定好 btnSort

func - 排序功能

我們先利用之前設定的 currentTime 大小來設定好排序的功能

    // 排序功能
    func sortMessages() {

        // 閉包寫法
        messageArray.sort { (messages1, messages2) -> Bool in

            //如果是升序就由小排到大,降序的話就由大排到小
            if isAscending {
                return messages1.currentTime < messages2.currentTime
            } else {
                return messages1.currentTime > messages2.currentTime
            }
        }
    }

func - 排序選項清單

接著我們利用 alert 來設計按下按鈕後會跳出選項清單的 func
我相信到這裡大家都會設定 func 了所以我主要講解 alertController 的用法

    // 排序選項清單
    func showSortOptions() {
    ...
    }

先設定好一個空的警告視窗 alertController

let alertController = UIAlertController(title: nil, 
                                        message: nil, 
                                        preferredStyle: .actionSheet)

接著依序按照我們前面設定的

  • isAscending 來改變他的排序方式
  • sortMessages() 利用前面的 isAscending 做排序
  • 最後呼叫 tableView 並 reloadData

我們用升序來做範例,降序就交給你們練習啦!

 // 升序選項
let ascendingAction = UIAlertAction(title: "舊到新", 
                                    style: .default) { [weak self] _ in

    self?.isAscending = true

    self?.sortMessages()

    self?.tbvTest.reloadData()
        }

最後要新增一個取消選項並把選項加進去 alertController 裡面!

        // 取消選項
        let cancelAction = UIAlertAction(title: "取消", 
                                         style: .cancel, 
                                         handler: nil)

        // 將上面的選項加入最開始命名的空的警告彈窗
        alertController.addAction(ascendingAction)
        alertController.addAction(descendingAction)
        alertController.addAction(cancelAction)

        // 這裡是設定彈出視窗是要從排序按鈕按才會彈出來
        if let popoverController = alertController.popoverPresentationController {
            popoverController.sourceView = btnSort
            popoverController.sourceRect = btnSort.bounds
        }

        // 呼叫出alerController
        present(alertController, animated: true, completion: nil)

IBAction

最後我們在 IBAction 中先設定好按下後要執行跳出排序選項清單

   @IBAction func btnSortSection(_ sender: Any) {
        showSortOptions()
    }

btnSent 設定

IBAction

送出按鈕就簡單了
我們先在 IBAction 設定按鈕功能

    // 送出按鈕
    @IBAction func btnSentAciton(_ sender: Any) {
        
        let realm = try! Realm()

        if btnSent.currentTitle == "送出" {
            if let user = txfUser.text, 
            let message = txvContent.text, 
            !user.isEmpty, 
            !message.isEmpty {
                let currentTime = getSystemTime()
                let newMessage = MessageBoard(name: user, 
                                              content: message, 
                                              currentTime: currentTime)

                try! realm.write {
                    realm.add(newMessage)
                }

                self.dataBase()

                txfUser.text = ""
                txvContent.text = ""
            } else {
                showAlert(message: "請輸入使用者名稱和內容")
            }
        }
    }

Func - getSystemTime

在 btnSent 我們需要用到 getSystemTime() 去取得系統時間
所以我們一樣簡單的來實作內容
這個用法在實作上很常會用到可以記起來喔!

    //取得系統時間
    func getSystemTime() -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter.string(from: Date())
    }

func - showAlert

我們在 btnSent 裡有用到顯示警告訊息的 func 提示使用者名稱和內容不能空值
這個用法也很常用所以要熟練喔

    //警告訊息
    func showAlert(message: String) {
        let alert = UIAlertController(title: "提示", 
                                      message: message, 
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "確定", 
                                      style: .default, 
                                      handler: nil))
        self.present(alert, 
                     animated: true, 
                     completion: nil)
    }

總結

今天的教學有比較多看起來複雜的東西,不過在實作上很實用所以要弄懂喔!


上一篇
Day17. Swift一定要會の留言板實作篇 (2)
下一篇
Day19. Swift一定要會の留言板實作篇 (4)
系列文
我將點燃Swiftの大海21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言